package cn.aws360.boot.base.api.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.Header;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * @author junnan
 */
@Slf4j
@UtilityClass
public class ServletUtils extends org.springframework.web.util.WebUtils {

    public HttpServletRequest getRequest() {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            return ((ServletRequestAttributes) requestAttributes).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    public HttpServletResponse getResponse() {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            assert requestAttributes != null;
            return ((ServletRequestAttributes) requestAttributes).getResponse();
        } catch (Exception e) {
            return null;
        }
    }

    public static String getClientIp() {
        return ServletUtil.getClientIP(getRequest());
    }

    public static UserAgent getUserAgent() {
        return UserAgentUtil.parse(getRequest().getHeader("User-Agent"));
    }

    public static JSONObject getPageJson() {
        String path = "templates/" + ServletUtils.getRequest().getRequestURI();
        String pageJson = ResourceUtil.readUtf8Str(path);
        return JSONObject.parseObject(pageJson);
    }

    public void renderJson(Object result) {
        HttpServletResponse response = getResponse();
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try (PrintWriter out = response.getWriter()) {
            out.append(JSONUtil.toJsonStr(result));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    public void renderFile(String fileName, byte[] content) {
        HttpServletResponse response = getResponse();
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        try {
            response.setHeader(Header.CONTENT_DISPOSITION.getValue(),
                    "attachment;filename=" + URLEncoder.encode(fileName, CharsetUtil.UTF_8));
            IoUtil.write(response.getOutputStream(), false, content);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
